package com.ltu.config;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**  
 * @Description: 配置线程池
 * @author: 若尘  
 * @date 2018年10月2日 下午3:25:30
 * @version V1.0  
 */

@Configuration
@EnableAsync
public class ThreadConfig {

	 	@Bean("customServiceExecutor")
	    public TaskExecutor customServiceExecutor(){
	        ThreadPoolTaskExecutor threadPoolTaskExecutor=new ThreadPoolTaskExecutor();
	        //线程核心数目
	        threadPoolTaskExecutor.setCorePoolSize(17);
	      //设置线程空闲时间
	        threadPoolTaskExecutor.setKeepAliveSeconds(180);
	      //空闲的情况下是否是否资源，默认false
	        threadPoolTaskExecutor.setAllowCoreThreadTimeOut(true);
	        //最大线程数
	        threadPoolTaskExecutor.setMaxPoolSize(128);
	        //配置队列大小
	        threadPoolTaskExecutor.setQueueCapacity(1000);
	        //配置线程池前缀
	        threadPoolTaskExecutor.setThreadNamePrefix("custom-service-");
	        /*配置拒绝策略
	         ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常
	        ThreadPoolExecutor.DiscardPolicy：丢弃任务，但是不抛出异常。
	        ThreadPoolExecutor.DiscardOldestPolicy：丢弃队列最前面。
	        ThreadPoolExecutor.CallerRunsPolicy：由调用者处理该任务 。*/
//	        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
	        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
	        //
	        threadPoolTaskExecutor.initialize();
	        return threadPoolTaskExecutor;
	    }
	
}
